#!/usr/bin/env python

#					 Copyright 2010 Morris Blackham
#
#
#	  This program is free software: you can redistribute it and/or modify
#	  it under the terms of the GNU General Public License as published by
#	  the Free Software Foundation, either version 3 of the License, or
#	  (at your option) any later version.
#
#	  This program is distributed in the hope that it will be useful,
#	  but WITHOUT ANY WARRANTY; without even the implied warranty of
#	  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
#	  GNU General Public License for more details.
#
#	  You should have received a copy of the GNU General Public License
#	  along with this program.	If not, see <http://www.gnu.org/licenses/>.


from lxml import etree
import time
import datetime
from datetime import date, timedelta
from time import strftime
import os
import shutil
#import logging
import sys
import sendemail
import commands
import fileinput


dateformat = "%m-%d-%y"
timeformat = "%H:%M"
shortformat = ('%m-%d')
sp = " "

# rundate is variable for testing,	it gets incremented on each run
# when runtest.py is launched

# use for runtest.py
#day = sys.argv[1]
#rundate = datetime.datetime.strptime(day, dateformat)

# use for normal mode
now = datetime.date.today()
day = now.strftime(dateformat)
rundate = datetime.datetime.strptime(day, dateformat)
logdate = rundate.strftime(shortformat) + sp + datetime.datetime.now().strftime(timeformat) + "  : "

#Set date/time formats for file names and timestamps

todayLong = rundate.strftime(dateformat)
yesterday = (rundate - timedelta(1)).strftime(dateformat)
msg = ""
logFile = ""


configfile = "/etc/opt/fbc/fbc.xml"
try:
	tree = etree.parse(configfile)
	root = tree.getroot()
except:
	print("config file %s file not found" % configfile)

#setup logging 

try:
	logpath = os.path.normpath(root.find("logpath").text)
except:
	logpath = os.getcwd()

if not os.path.isdir(logpath):
	try:
		os.makedirs(logpath)
	except:
		print("Unable to create log path %s" % logpath)

loglevel = root.find("loglevel").text

# check if all the binaries and other scripts are in place
gwtmstmp = "/opt/novell/groupwise/agents/bin/gwtmstmp"
dbscript = "/opt/fbc/dbcopy.sh"
if not os.path.isfile(dbscript):
	print 'dbcopy.sh script not found, Please install before continuing.'
db = "/opt/novell/groupwise/agents/bin/dbcopy"
if not os.path.isfile(db):
	print 'dbcopy not found.  Please install before continuing.'
tarscript = "/opt/fbc/fbctar.sh"
if not os.path.isfile(tarscript):
	print("Tar shell script not found.	Please check installation")
	
# assign vars from the config file array
backuppath = root.find("backuppath").text

# see if gwtimestamp is enabled
gwts = root.find("gwtimestamp").text
if gwts == "yes":
	if not os.path.isfile(gwtmstmp):
		print("gwtmstmp binary not found,  You must install GW agents to set timestamp")
		gwts == "no"
	
maxinc = int(root.find("maxinc").text)
mountpath = os.path.normpath(root.find("mountpath").text)
offlinepath = os.path.normpath(root.find("offlinepath").text)
temppath = os.path.normpath(root.find("temppath").text)
tardirectory = os.path.normpath(root.find("tarpath").text)

# TO DO:  need to find a way to age out old tar files
#tarage = root.find("tarage").text

startday = root.find("startday").text
sendlog = root.find("sendlog").text
smtphost = root.find("smtphost").text
recipient = root.find("emailaddr").text
sp = " "
lockfile = "/etc/opt/fbc/fbc.lock"

class logger:

	def __init__(self,logFile):
		self.logFile = logFile		

	def debug(self,msg):
		if loglevel == "Verbose":
			logfile = open(self.logFile, 'a')
			logfile.write(logdate + msg + '\n')
			logfile.close()
		return

	def info(self,msg):
		logfile = open(self.logFile, 'a')
		logfile.write(logdate + msg + '\n')
		logfile.close()
		return

	def error(self,msg):
		logfile = open(self.logFile, 'a')
		logfile.write(logdate + msg + '\n')
		logfile.write(logdate + "Critical Error encountered! Exiting program.\n") 
		print("Critical ERROR encountered: %s " % msg)
		print("Exiting program!")
		quit()


def senderror(errortext):

	# Function to send error email,	need to add instances of when to send...

	subject = 'FreebieCopy error found on	%s' % todayLong
	message = """\
	FreebieCopy encountered the following error:
	%s
	""" % errortext
	
	sender = 'admin@freebie.blah.com'
	attachment = 'blank'
	sendemail.send(smtphost, sender, recipient, subject, message, attachment)
	return


def removeall(path):

	# Function to delete all files from a directory,

	if not os.path.isdir(path):
		return
	else:
		shutil.rmtree(path)	

def rewritelock(replacestring):
	
	f = open(lockfile,'r')
	contents = f.readline()
	f.close()
	for line in fileinput.input(lockfile, inplace=1):
		if contents in line:
			 line = line.replace(contents,(replacestring + "\n"))
		sys.stdout.write(line)

	
def tarcleanup():
	
	#	TO DO:	need  some code here to check the tar directory and either delete
	#	old tars or scp (or some other method) to offline storage
	#	OR,  make it a separate script,	prbly a shell script

	return


def checkspace(source, volume):

	# Function to check if we have enough diskspace available
	#walk the mounted domain or po directory and get the size

	fsize = 0
	for (path, dirs, files) in os.walk(source):
		for file in files:
			filename = os.path.join(path, file)
			if os.path.exists(filename):
				fsize += os.path.getsize(filename)

	# mulitply by 2 to make sure we really have enough
	safesize = fsize * 2

	# get available diskspace for volume where target directory is located
	stats = os.statvfs(volume)
	freespace = (stats.f_bavail * stats.f_frsize) 
	
	# check if free space is greater than the safe size
	if freespace > safesize:
		pass
	else:
		errortext = "Insufficient disk space to continue!	Exiting"
		logging.error(errortext)
		log.error(errortext)
	
	return


def bktype():
	
	# Function to set what type of backup will be run; full or incremental?

	global backuptype
	global object
	global objectdir
	global currentinc

	logging.debug("Determining object type and backup type")

	#find if it's a domain or post office
	if e.find("type").text == "po":
		object = 1
		#logging.debug("object = post office")
		currentinc = e.find("currentinc").text

		#have to set current inc to something or script blows chunks
	
		if currentinc ==	None:
			currentinc = maxinc
		else:
			currentinc = int(e.find("currentinc").text)

	elif e.find("type").text == "domain":
		object = 0
		#logging.debug("object type is domain")
	else:
		logging.error("Object type is not set to domain or po, please check configuration")

	# check to see if it's Sun, or other defined start day
	#	or if the currentinc is blank,
	
		#logging.debug("DEBUG: current incremental number is %s" % currentinc)


	# !!!!!!!  
	# next line remarked out for testing purposes..  need to unrem for ship.

	#if rundate.strftime("%a") == startday or currentinc == maxinc:

	if object == 0:
		backuptype = 0
		logging.info("Performing a full backup for %s." % e.find("name").text)

	elif object == 1:
		if currentinc == maxinc:
			backuptype = 1
			logging.info("Performing a full backup for %s." % e.find("name").text)

		# else if the current incremental is less than the max incremental setting

		elif currentinc < maxinc and object == 1:
			logging.info("Performing an incremental backup for %s." % e.find("name").text)
			backuptype = 2

		# else if none of the above match,	we'll do a full backup 

	else:
		logging.info("Performing a full backup for %s." % e.find("name").text)
		backuptype = 0

	#logging.debug("DEBUG: backup type is %s" % backuptype)
	
	return


def getsource():

# defines the source directory for dbcopy

	global source
	global objectdir

	# gets the domain or po directory name from the remote path

	if e.find("remotepath").text != None:
		objectdir =  os.path.basename(e.find("remotepath").text)
	else:
		logging.error("Remote Path is not set for $s.	Please check configuration." % objectdir)

	#sets the source path to the mount point, creates it if not found under the mount point

	if mountpath != None:
		source = os.path.join(mountpath, objectdir)
		logging.info("Source directory is %s " % source)
	else:
		logging.error("Mount point path not set in config file.	Please check configuation")
	if not os.path.isdir(source):
		try:
			os.makedirs(source) 
			logging.debug("Source directory not found. Creating: %s" % source)
		except:
			logging.error("Unable to create mount path: %s" % source)

	# checks if this server is a dom or po,  then checks
	# if the .db is there,	this is how to check if
	# the remote filesystem is mounted

	if object == 1:
		dbfile = "wphost.db"
	elif object == 0:
		dbfile = "wpdomain.db"
	else:
		logging.error("object type is not set")

	dbpath = os.path.join(source, dbfile)

	# if the .db is not found,	let's mount it.

	if not os.path.isfile(dbpath):
		logging.debug("Remote directory is not mounted - mounting %s" % source)
	
		#gets the user, password, remotepath and IP from xml and
		# mounts the dir

		remoteuser =  e.find("remoteuser").text
		if remoteuser == None:
			logging.error("Remote user not found for this object.	Check configuration")
		remotepass =  e.find("remotepass").text
		if remotepass == None:
			logging.error("Remote password for this object not found.	Check configuration")
		ipaddr = e.find("ipaddr").text
		if ipaddr == None:
			logging.error("IP Address for this object not found.	Check configuration")
		remotepath = e.find("remotepath").text
		if remotepath == None:
			logging.error("Remote path not found.	Check configuration")

		mounttype = e.find("mounttype").text
		
		#find mount type; samba or ncp

		if mounttype == None:
			logging.error("Mount type not found.  Check configuration")

		elif mounttype == "samba" or mounttype == "Samba":
			mount = "/sbin/mount.cifs"
	
			# sets up the command to mount the remote file system

			mountargs = ("-o username=" + remoteuser + ",password=" + remotepass + ",ip=" + ipaddr + ",rw")
			#logging.debug("mount arguments are %s" % mountargs)
			mountcmd = (mount + sp + remotepath + sp + source + sp + mountargs)

		else:
			mount = "ncpmount"
			if not os.path.isfile('/usr/bin/ncpmount'):
				logging.error("ncpmount command not found.	please install ncpfs package")

			#need to check and accomodate what the remote path ncp string is

			if remotepath.startswith('//'):
				x = remotepath.split('/',3)
			elif remotepath.startswith('/'):
				x - remotepath.split('/',2)	
			else:
				x = remotepath.split('/',1)

			server = x[-2]
			vol = x[-1]			
	
			mountargs = ("-S " + server + " -A " + ipaddr + " -V " + vol + " -U " + remoteuser + " -P " + remotepass)
			mountcmd = (mount + sp + mountargs + sp + source)
		
		# mount the remote file system

		try:
			os.system(mountcmd)
		except:
			logging.error("Mount failed for $s" % mountcmd)
	
	# create some symlinks from the mounted po to a temp area to 
	# only do dbcopy of the user and msg.db's
	# only needed for a PO incremental backup

	if backuptype == 2:
		logging.debug("Backup type is incremental for post office")

		# sets the link path under the fbc/tmp dir, then creates it if not found

		linkpath = os.path.join(temppath, objectdir)
		logging.debug("DEBUG: temporary link path is %s" % linkpath)
		if not os.path.isdir(linkpath):
			logging.info("Creating temporary directory with sym links %s for incremental backup." % linkpath)		 
			try:
				os.makedirs(linkpath)
			except:
				logging.error("Could not create temporary directory %s" % linkpath)

		# set up array of files/dirs to create links for
		# then iterate thru the array and create the symlinks
		# except for offiles dir

		gwlist = (["wphost.db", "gwpo.dc", "ngwguard.db", "ngwguard.rfl", "ngwguard.fbk","ngwguard.dc","ngwcheck.db", "ofuser", "ofmsg", "gwdms", "ofviews"])

		for a in gwlist:
			sourcelink = os.path.join(source, a)
			targetlink = os.path.join(linkpath, a)
			try:
				if not os.path.islink(targetlink):
					os.symlink(sourcelink, targetlink)					
			except:
				logging.error("Could not create symbolic link for %s" % targetlink)
				continue

		# now set the dbcopy source to the tmp/po directory

		source = linkpath
		logging.info("Source path for incremental backup is: %s" % source)

	return


def needtar():

	# this will check if an existing backup exists in the target directory,
	# also check if any backups are older than maxinc value
	# for po's we're tarring all incrementals with it's full backup and starting
	# fresh with a new full backup.
	# if so,  tar it up in the fbc/tars/domain or po) directory

	global basepath

	logging.debug("Determining if old backup's should be tarred.")

	def tarprep(tardir):
	
	#function to create variables and call createtar() function

		global tarsource
		tarsource = os.path.join(basepath, tardir)
		logging.info("Tarring existing backup directory: %s " % tardir)
		createtar(tarsource, tardir)

		return

	# for a full po backup type  

	if backuptype == 1:
		if basepath != None:
			try:
				list = sorted(os.listdir(basepath))
			except:
				logging.error("getting list of directory %s failed" % basepath)


			# get the last full backup path			

			p1 = os.path.basename(e.find("currentfullpath").text)[0:8]

			# setup 2 arrays, one for incremental backup dirs, one for full

			incdir = [elem for elem in list if elem.split('-')[3] == 'inc']
			fulldir = [elem for elem in list if elem.split('-')[3] == 'full']

			# we're going to tar all incrementals and their respective full backups
			# need to do the incrementals first

			for y in incdir:
				backdir = y[0:8]
				tardir = y 
				tarprep(tardir)

			#now tar the full backups,	except for today's

			for z in fulldir:
				backdir = z[0:8]
				if p1 == None or z == os.path.basename(target):
					pass
				else:
					if backdir != p1:
						tardir = z 
						tarprep(tardir)
		else:
			logging.error("Basepath not set, Can't determine what directory to check.")
	
	# now tar old domain backups

	elif object == 0:
		oldpath = os.path.join(target, "wpdomain.db")

		if not os.path.isfile(oldpath):
			pass
		else:
			tarsouce = target
			tardir = os.path.basename(target)
			createtar(tarsource, tardir)
	
		if currentfulldate != None:

			# get's the last full backup date from xml to use as "latest"

			latest = datetime.datetime.strptime(currentfulldate, dateformat)

			list = os.listdir(basepath)
			for y in list:
				try:
					t = datetime.datetime.strptime(y, dateformat)
				except:
					continue

				# check dates of all backup directorys,  then tar it if it's older
				# than today's (latest) minus the maxinc number

				if (latest - t) > timedelta(maxinc - 1):
					tardir = y
					tarsource = os.path.join(basepath, y)				
					createtar(tarsource, tardir)

	else:
		pass					
	
	return


def createtar(tarsource, tardir):

	#function to create a tar of an existing backup

	logging.info("Tarring existing backup in directory %s" % tardir)

	# create base directory if not found

	tarpath = os.path.join(tardirectory, objectdir)
	if not os.path.isdir(tarpath):
		try:
			os.makedirs(tarpath)
		except:
			logging.error("Failed to create base tar directory %s" % tarpath)

	# set som vars and proceed

	tarfile = os.path.join(tarpath, tardir[0:8]) + ".tar"

	#logging.debug("DEBUG: tarfile = %s" % tarpath)

	tarargs = (tarfile + sp + tarsource)
	#logging.debug("DEBUG: tarargs = %s" % tarargs)
	tarcmd = (tarscript + sp + tarargs +">/dev/null")
	#logging.debug("DEBUG: tar command should be %s " % tarcmd)
	logging.info("Creating tarfile: %s" % tarfile)

	# check available disk space and then call the tarscript
	
	checkspace(tarsource, tardirectory)

	try:
		os.system(tarcmd)
	except:
		logging.error("Creation of tar file %s failed" % tarfile)
	
	logging.info("Removing old directory %s " % tarsource)

	# now remove the old directory

	removeall(tarsource)

	# just to make sure... may remove the following or the function later.

	if os.path.isdir(tarsource):
		try:
			logging.error("%s directory is still here,	what up with that?" % tarsource)
			os.rmdir(tarsource)
		except:
			logging.info("Failed to remove old directory %s" % tarsource)

	return


def prepareblob():

	# Function to setup links to copy offiles dir from the latest full 
	# backup directory

	global blobtarget
	global blobsource

	if e.find("currentfullpath") == None:
		logging.debug("DEBUG: Current full path not set.	It should be!")
		quit()
	else:
		blobtarget = os.path.normpath(e.find("currentfullpath").text)
		blobsource = os.path.join(mountpath, objectdir)

	symsource = os.path.join(blobtarget, "offiles")
	symtarget = os.path.join(target, "offiles")

	try:
		os.symlink(symsource, symtarget)
		logging.info("Creating symbolic link to offiles")
	except:
		logging.error("Failed to create offiles symlink")
		pass
	
	return


def gettarget():

	# function to set the target directory for dbcopy

	global restorepath
	global target
	global basepath
	global blobsource
	global blobtarget
	global tarsource
	global currentinc

	#create base directory for xml file

	basepath = os.path.join(backuppath, objectdir)
	for el in e.iter("basepath"):
		el.text = basepath	

	# if this is a full backup, set target path to backup/domain(po)/date
	
	if object == 0:
		target = os.path.join(basepath, todayLong)

		logging.info("DBCopy target path is %s" % target)

		currentfullpath = target
		for el in e.iter("currentfullpath"):
			el.text = currentfullpath

		for el in e.iter("currentfulldate"):
			el.text = currentfulldate

	# for po full

	elif backuptype == 1:
		
		#logging.debug("DEBUG: backup type is %s" % backuptype)
		
		target = os.path.join(basepath, todayLong + '-full')

		# set currentfullpath to target,	then resets currentinc to 1
		currentfullpath = target
		for el in e.iter("currentfullpath"):
			el.text = currentfullpath
		for el in e.iter("currentfulldate"):
			el.text = currentfulldate
		currentinc = "1"
		for el in e.iter("currentinc"):
			el.text = currentinc

	elif backuptype == 2:

		target = os.path.join(basepath, todayLong + "-inc")	

		#set the current full date 
		for el in e.iter("currentfulldate"):
			el.text = currentfulldate

		currentinc += 1

		for element in e.iter("currentinc"):
			element.text = str(currentinc)

	# create the target dir if not found
	logging.info("Target directory for backup is %s" % target)

	if not os.path.isdir(target):
		logging.debug("Target directory not found, creating %s" % target)
		os.makedirs(target)

	needtar()

	restorepath = target
	for el in e.iter("restorepath"):
		el.text = restorepath

	if backuptype == 2:
		prepareblob()
	
	return


def docopy(source, target):


	checkspace(source, target)
	dbargs =  source + sp + target
	dbcmd = dbscript + sp + str(backuptype) + sp + dbargs + sp + yesterday 

	result = commands.getstatusoutput(dbcmd)
	if result[0] == 0:
		pass
	else:
		print 'DBCopy failed with error status %s' % result[0]

	return

def copy():

	# Function to start the copy process

	#global currentinc
	#global restorepath
	global args
	global starttime
	global endtime
	global objectname

	# get time for timestamp before the copy starts 
	timestamp = rundate.strftime(timeformat)

	#logging.debug("Timestamp is %s" % timestamp)

	# sets the dbcopy command with its arguments
	logging.info("Starting DBCopy for %s" % e.find("name").text) 

	#call the doopy function 
	docopy(source, target)

	if backuptype == 2:
		# args = " -b -m"
		# copy offiles to the last full po backup
		logging.info("Starting DBCopy to copy OFFILES for %s" %e.find("name").text)
		
		docopy(blobsource, blobtarget)

		#make sure we get the wphost.db
		hostsource = os.path.join(source, "wphost.db")
		hosttarget = os.path.join(target, "wphost.db")
		try:
			shutil.copyfile(hostsource, hosttarget)	
		except:
			logging.error("Failed to copy wphost.db!")	
		
	# check to see if the timestamp is required,  then runs the gwtmstmp command
	if object == 1 and gwts == "yes":
		logging.info("Setting GroupWise time stamp for %s" % e.find("name").text)
		tssource = os.path.join(mountpath, objectdir)
		tsargs = (" -p " + tssource + " -s -t " + timestamp)
		tscmd = gwtmstmp +	tsargs

		try:
			os.system(tscmd)
		except:
			logging.error("%s timestamp command failed." % tsmd)

	else:
		logging.debug("GW timestamp setting not enabled. Not setting timestamp")
			
	# create a restore path if not found,	then create a symlink pointing to
	# the most current backup

	offlinedir = os.path.join(offlinepath, objectdir)
	if not os.path.isdir(offlinepath):
		os.makedirs(offlinepath)
		
	if os.path.islink(offlinedir):
		os.unlink(offlinedir)

	try:
		os.symlink(restorepath, offlinedir)
	except:
		logging.error("Creation of sym links failed")
	
	#unmount the source - can't mount a ncp server twice..
	if backuptype == 2:
		unmount = "umount " + blobsource
		
		#remove symlinks from the temp dir
		rmlink = os.path.join(temppath, objectdir)
		logging.debug("Removing symbolic links from %s" % rmlink)
		removeall(rmlink)
		command_result = commands.getstatusoutput(unmount)

		#wait until the umount command succeeds.
		while command_result[0] != 0:
			time.sleep(10)
			command_result = commands.getstatusoutput(unmount)

	else:
		unmount = "umount " + source
		command_result = commands.getstatusoutput(unmount)
		while command_result[0] != 0:
			time.sleep(10)
			command_result = commands.getstatusoutput(unmount)

	return


def writexml():

	# Function to write all the changed data back to the config file
		
	try:
		tree.write(configfile, pretty_print=True)
	except:
		logging.error("Failed to update config file")

def main():

	global e
	global currentfulldate
	global currentinc
	global objectname
	global logging
	global log
	global mainlog
	
	#create instance for the main log file
	mainlog = (os.path.join(logpath, datetime.datetime.strftime(rundate, shortformat)) + ".log")
	log = logger(mainlog)

	# and start the main log file
	log.info("Starting FreebieCopy for %s" % rundate.strftime(dateformat))
	log.info("===========================================")
	log.info(" ")

	currentfulldate = todayLong

	lastrundate = rundate.strftime(dateformat)

	for el in root.iter("lastrundate"):
		el.text = lastrundate
	
	lastrunstart = (rundate.strftime(dateformat) + sp + datetime.datetime.now().strftime(timeformat))

	for el in root.iter("lastrunstart"):
		el.text = lastrunstart

	# create a lock file so web admin doesn't write to the xml file during 
	# running of this script 
	if not os.path.isfile(lockfile):
		lock = open(lockfile, 'w')
		text = "blank"
		try:
			lock.write(text)
			log.info("Creating lockfile: %s" % lockfile)
		except:
			log.error("Failed to create lock file: %s" % lockfile)
	
		lock.close()

	# iterate thru all GW objects in the xml and 
	# do the  copy
	for e in root.findall("./server"):
		restorepath = e.find("restorepath").text
		starttime = (rundate.strftime(dateformat) + sp + datetime.datetime.now().strftime(timeformat))

		for el in e.iter("starttime"):
				el.text = starttime

		objectname = e.find("name").text

		#create instance for domain/po log file
		agentlogpath = os.path.join(logpath, objectname)
		if not os.path.isdir(agentlogpath):
			try:
				os.makedirs(agentlogpath)
			except:
				print("Unable to create log path %s" % agentlogpath)

		agentlog = (os.path.join(agentlogpath, datetime.datetime.strftime(rundate, shortformat)) + ".log")

		# 'logging' is for dom/po log,	'log' is for main log

		logging = logger(agentlog)

		log.info("Performing backup for %s" % objectname)

		logging.info("===========================================")
		logging.info(" ")
		logging.info("Starting backup for %s" % objectname)

		# add object name to lock file,  so web admin can see what's currently running.
		rewritelock(objectname)
		bktype()
		getsource()
		gettarget()
		copy()
		
		endtime = rundate.strftime(dateformat) + sp + datetime.datetime.now().strftime(timeformat)
		for el in e.iter("endtime"):
			el.text = endtime



		logging.info("Backup for %s complete." % objectname)
		logging.info("-----------------------------------------------")

		log.info("Backup for %s complete." % objectname)
		log.info("-----------------------------------------------")


	
	lastrunend = rundate.strftime(dateformat) + sp + datetime.datetime.now().strftime(timeformat)
	for el in root.iter("lastrunend"):
		el.text = lastrunend



	log.info("Writing updates to config file")

	writexml()	

	tarcleanup()

	# kill the lock file
	if os.path.isfile(lockfile):
		os.remove(lockfile)
		log.info("Removing lock file.")
	else:
		log.error("Unable to delete lock file!!")

	log.info(" ")
	log.info("To see log files for domains and post office,")
	log.info("Go to %s/ domainname/poname" % logpath)
	log.info(" ")
	log.info("========== FreebieCopy Finished ===========")
	log.info(" ")

	return


def sendlog():

	#function to email log file to admin.

	subject = 'FreebieCopy status for %s' % todayLong
	message = 'Attached is the log file for this run'
	sender = 'admin@freebie.blah.com'

	try:
		sendemail.send(smtphost, sender, recipient, subject, message, mainlog)
		log.info("Log file sent to %s" % recipient)
	except:
		log.info("Unable to send log file")

	log.info("==========================================")
# now everthings defined,	let's run this puppy!

main()
if sendlog == "Yes":
	sendlog()	
	
